<template>
  <div class="users-container">
    <el-card class="search-card" shadow="hover">
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="请输入姓名或设备号"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><RefreshRight /></el-icon>重置
        </el-button>
      </div>
      <div class="filter-area">
        <el-select v-model="ageRange" placeholder="年龄范围" clearable>
          <el-option label="18岁以下" value="under18" />
          <el-option label="18-25岁" value="18-25" />
          <el-option label="26-35岁" value="26-35" />
          <el-option label="36-45岁" value="36-45" />
          <el-option label="45岁以上" value="above45" />
        </el-select>
        <el-select v-model="scoreRange" placeholder="分数范围" clearable>
          <el-option label="60分以下" value="under60" />
          <el-option label="60-70分" value="60-70" />
          <el-option label="71-80分" value="71-80" />
          <el-option label="81-90分" value="81-90" />
          <el-option label="91-100分" value="91-100" />
        </el-select>
        <!-- <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        /> -->
      </div>
    </el-card>

    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-operations">
            <el-button type="primary" plain @click="exportUserData">
              <el-icon><Download /></el-icon>导出数据
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="userTableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.gender === '男' ? 'primary' : 'success'"
              size="small"
            >
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="通关分数" width="100">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="completionTime" label="完成时间/min" width="180" />
        <el-table-column prop="completionRate" label="任务完成率" width="120">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.completionRate"
              :color="getProgressColor(scope.row.completionRate)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备号" width="120" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="viewUserDetail(scope.row.id)"
            >
              查看详情
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="evaluateUser(scope.row.id)"
            >
              评价
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5,10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalUsers"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户评价对话框 -->
    <el-dialog
      v-model="evaluationDialogVisible"
      title="用户综合评价"
      width="60%"
    >
      <div class="evaluation-container">
        <div class="user-basic-info">
          <div class="user-avatar">
            <el-avatar :size="64" :src="currentUser.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
          </div>
          <div class="user-info">
            <h3>{{ currentUser.name }}</h3>
            <p>ID: {{ currentUser.id }}</p>
            <p>完成时间: {{ currentUser.completionTime }}</p>
            <p>通关分数: <span :class="getScoreClass(currentUser.score)">{{ currentUser.score }}</span></p>
          </div>
        </div>

        <div class="evaluation-chart-container">
          <div id="ability-radar-chart" class="evaluation-chart"></div>
        </div>

        <div class="evaluation-form">
          <el-form :model="evaluationForm" label-width="100px">
            <el-form-item label="综合评语">
              <el-input
                v-model="evaluationForm.comment"
                type="textarea"
                :rows="4"
                placeholder="请输入对该用户的综合评价..."
              />
            </el-form-item>
            <el-form-item label="火灾知识">
              <el-rate
                v-model="evaluationForm.fireKnowledge"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="完成效率">
              <el-rate
                v-model="evaluationForm.efficiency"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="应变能力">
              <el-rate
                v-model="evaluationForm.adaptability"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="操作熟练度">
              <el-rate
                v-model="evaluationForm.operationSkill"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="团队协作">
              <el-rate
                v-model="evaluationForm.teamwork"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">保存评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { API_BASE_URL } from '@/utils/constants'

const router = useRouter()

// 搜索和筛选
const searchQuery = ref('')
const ageRange = ref('')
const scoreRange = ref('')
const dateRange = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(5)
const totalUsers = ref(0)

// 表格数据
const loading = ref(false)
const userTableData = ref([])

// 评价对话框
const evaluationDialogVisible = ref(false)
const currentUser = ref({})
const evaluationForm = reactive({
  comment: '',
  fireKnowledge: 0,
  efficiency: 0,
  adaptability: 0,
  operationSkill: 0,
  teamwork: 0
})

// 评分颜色
const rateColors = ['#F56C6C', '#E6A23C', '#909399', '#67C23A', '#409EFF']

// 雷达图实例
let abilityRadarChart = null

// 模拟数据
const mockUserData = () => {
  const users = []
  for (let i = 1; i <= 100; i++) {
    const score = Math.floor(Math.random() * 41) + 60 // 60-100
    const completionRate = Math.floor(Math.random() * 31) + 70 // 70-100
    users.push({
      id: i,
      name: `用户${i}`,
      age: Math.floor(Math.random() * 40) + 18, // 18-57
      gender: Math.random() > 0.5 ? '男' : '女',
      score: score,
      completionTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24)}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
      completionRate: completionRate,
      deviceId: `VR-${Math.floor(Math.random() * 1000) + 1000}`
    })
  }
  return users
}

// 获取用户数据（替换原模拟数据方法）
const fetchUserData = async () => {
  loading.value = true
  
  try {
    // 调用真实接口
    const response = await axios.get(`${API_BASE_URL}/user/users`)
    
    // 检查接口状态码
    if (response.data.code === 1) {
      // 数据转换（后端字段→前端字段）
      const rawData = response.data.data.map(item => ({
        id: item.userId,
        name: item.username,
        age: item.age,
        gender: item.gender === 'Male' ? '男' : '女',
        score: item.score,
        completionTime: item.completionTime,
        completionRate: item.completionRate,
        deviceId: item.deviceId
      }))
      
      // 应用筛选逻辑（保持原有筛选逻辑不变）
      let filteredUsers = [...rawData]
      
      // 搜索查询
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filteredUsers = filteredUsers.filter(user => {
          const nameMatch = user.name?.toLowerCase().includes(query) || false;
    // const idMatch = user.id?.toString().includes(query) || false;
    const deviceMatch = user.deviceId?.toLowerCase().includes(query) || false;
    return nameMatch|| deviceMatch;}
        )
      }
      
      // 年龄筛选
      if (ageRange.value) {
        filteredUsers = filteredUsers.filter(user => {
          const age = user.age
          switch(ageRange.value) {
            case 'under18': return age < 18
            case '18-25': return age >= 18 && age <= 25
            case '26-35': return age >= 26 && age <= 35
            case '36-45': return age >= 36 && age <= 45
            case 'above45': return age > 45
            default: return true
          }
        })
      }
      
      // 分数筛选
      if (scoreRange.value) {
        filteredUsers = filteredUsers.filter(user => {
          const score = user.score
          switch(scoreRange.value) {
            case 'under60': return score < 60
            case '60-70': return score >= 60 && score <= 70
            case '71-80': return score >= 71 && score <= 80
            case '81-90': return score >= 81 && score <= 90
            case '91-100': return score >= 91 && score <= 100
            default: return true
          }
        })
      }

      // 日期筛选（需要先启用日期选择器）
      if (dateRange.value && dateRange.value.length === 2) {
        const [startDate, endDate] = dateRange.value
        filteredUsers = filteredUsers.filter(user => {
          const userDate = new Date(user.completionTime)
          return userDate >= new Date(startDate) && userDate <= new Date(endDate)
        })
      }

      // 更新表格数据
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      userTableData.value = filteredUsers.slice(start, end)
      totalUsers.value = filteredUsers.length
      
    } else {
      ElMessage.error(response.data.message || '数据加载失败')
    }
    
  } catch (error) {
    console.error('接口请求失败:', error)
    ElMessage.error('网络请求异常，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  fetchUserData()
}

const resetSearch = () => {
  searchQuery.value = ''
  ageRange.value = ''
  scoreRange.value = ''
  dateRange.value = []
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserData()
}

// 评分样式
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-medium'
  return 'score-poor'
}

// 进度条颜色
const getProgressColor = (score) => {
  if (score >= 90) return '#67C23A'
  if (score >= 80) return '#409EFF'
  if (score >= 70) return '#E6A23C'
  return '#F56C6C'
}

// 查看用户详情
const viewUserDetail = (userId) => {
  router.push(`/user-detail/${userId}`)
}

// 评价用户
const evaluateUser = (userId) => {
  // 模拟获取用户数据
  const user = userTableData.value.find(u => u.id === userId)
  if (user) {
    currentUser.value = user
    evaluationDialogVisible.value = true
    // 重置表单
    Object.keys(evaluationForm).forEach(key => {
      evaluationForm[key] = 0
    })
    evaluationForm.comment = ''
    // 初始化雷达图
    nextTick(() => {
      initRadarChart()
    })
  }
}

// 初始化雷达图
const initRadarChart = () => {
  if (abilityRadarChart) {
    abilityRadarChart.dispose()
  }
  
  const chartDom = document.getElementById('ability-radar-chart')
  abilityRadarChart = echarts.init(chartDom)
  
  const option = {
    radar: {
      indicator: [
        { name: '火灾知识', max: 5 },
        { name: '完成效率', max: 5 },
        { name: '应变能力', max: 5 },
        { name: '操作熟练度', max: 5 },
        { name: '团队协作', max: 5 }
      ]
    },
    series: [{
      type: 'radar',
      data: [{
        value: [0, 0, 0, 0, 0],
        name: '能力评估'
      }]
    }]
  }
  
  abilityRadarChart.setOption(option)
}

// 监听评分变化更新雷达图
watch([() => evaluationForm.fireKnowledge,
  () => evaluationForm.efficiency,
  () => evaluationForm.adaptability,
  () => evaluationForm.operationSkill,
  () => evaluationForm.teamwork
], () => {
  if (abilityRadarChart) {
    abilityRadarChart.setOption({
      series: [{
        data: [{
          value: [
            evaluationForm.fireKnowledge,
            evaluationForm.efficiency,
            evaluationForm.adaptability,
            evaluationForm.operationSkill,
            evaluationForm.teamwork
          ]
        }]
      }]
    })
  }
})

// 提交评价
const submitEvaluation = () => {
  // 这里应该调用API保存评价数据
  ElMessage.success('评价提交成功')
  evaluationDialogVisible.value = false
}

// 导出用户数据
const exportUserData = () => {
  const data = userTableData.value.map(user => ({
    ID: user.id,
    姓名: user.name,
    年龄: user.age,
    性别: user.gender,
    通关分数: user.score,
    完成时间: user.completionTime,
    任务完成率: user.completionRate,
    设备号: user.deviceId
  }))

  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '用户数据')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '用户数据.xlsx')
}

// 生命周期钩子
onMounted(() => {
  fetchUserData()
})

onUnmounted(() => {
  if (abilityRadarChart) {
    abilityRadarChart.dispose()
  }
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  width: 300px;
}

.filter-area {
  display: flex;
  gap: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-excellent {
  color: #67C23A;
  font-weight: bold;
}

.score-good {
  color: #409EFF;
  font-weight: bold;
}

.score-medium {
  color: #E6A23C;
  font-weight: bold;
}

.score-poor {
  color: #F56C6C;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.evaluation-container {
  padding: 20px;
}

.user-basic-info {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.user-info h3 {
  margin: 0 0 10px 0;
}

.user-info p {
  margin: 5px 0;
}

.evaluation-chart-container {
  margin-bottom: 30px;
}

.evaluation-chart {
  width: 100%;
  height: 300px;
}
</style>